<template>
  <div class="my-bar" v-loading="loading">
    <div id="main3"></div>
  </div>
</template>
<script setup lang='ts'>
import { ref, reactive, watch, onBeforeUnmount } from 'vue'
import { countryListApi } from '@/views/workbench/api/workbenchApi'
import { useRoute } from 'vue-router'
import { getUserInfo } from '@/global/session'
import * as echarts from 'echarts'
const route = useRoute()
const townId = route.query.townId as string
let userInfo = reactive({ roleId: '', townId: '', countryId: '', roleAuth: '' })
userInfo = JSON.parse(getUserInfo() as string)

const loading = ref<boolean>(false)
interface PropsDialog {
  resize: boolean;//浏览器是否变化
}
const props = withDefaults(defineProps<PropsDialog>(), {
  resize: false,
});

const onList = async () => {
  try {
    let res = await countryListApi({ id: townId })
    if (res?.code === 0) {
      let [arr1, arr2] = [<any>[], <any>[]]
      res.data.forEach((v: any) => {
        arr1.push(v.countryName)
        arr2.push(v.intoNum)
      });
      echartsFun(arr1, arr2)
    } else {
      loading.value = false
    }
  } catch {
    loading.value = false
  }
}
//如果是乡镇账号 判断一下 是不是当前乡镇
if (userInfo.roleId == '4' || userInfo.roleId == '5') {
  if (userInfo.townId === townId) {
    loading.value = true
    onList()
  }
} else {
  loading.value = true
  onList()
}
// 入户进度图 绘制图表
const echartsFun = (arr1, arr2) => {
  let myChart = echarts.init(document.getElementById('main3') as unknown as HTMLDivElement)
  let optionMap = {
    grid: {
      left: '60px',
      top: '10px',
      bottom: '60px',
      right: '20px'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: arr1,
      axisLabel: {
        rotate: 60
      },
      axisTick: { // 刻度线
        show: false
      },
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      min: 0,
      max: function (value) {
        if (value.max < 5) {
          return 5
        }
      }, // 左侧y轴最大值
    },
    label: {
      rotate: 10
    },
    barWidth: 22,//柱子宽度
    series: [
      {
        data: arr2,
        type: 'bar',
        itemStyle: {
          color: '#447ad2',
          barBorderRadius: [20, 20, 0, 0],

        }
      }
    ]
  };
  myChart.setOption(optionMap);
  loading.value = false
}

//浏览器是否变化
watch(
  () => props.resize,
  () => {
    let myChart = echarts.init(document.getElementById('main3') as unknown as HTMLDivElement)
    myChart.resize()
  }
)
//注销之前
onBeforeUnmount(() => {
  let myChart = echarts.init(document.getElementById('main3') as unknown as HTMLDivElement)
  myChart.dispose()
})
</script>
<style scoped lang='scss'>
.my-bar {
  width: 100%;
  height: 100%;

  >div {
    width: 100%;
    height: 100%;
  }
}
</style>